package anagram;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Anagram
{

    private String originalString;
    private String mixedString;

    public Anagram(String original, String mixedUp)
    {
        this.originalString = original.toLowerCase();
        this.mixedString = mixedUp.toLowerCase();
    }

    public boolean isValid()
    {
        Stack<Character> originalStringStack = new Stack<Character>();
        char[] originalStringCharArray = originalString.toCharArray();
        for ( int i = 0; i < originalStringCharArray.length; i++ )
        {
            if ( isLetter(originalStringCharArray[i]) )
            {
                originalStringStack.add(originalStringCharArray[i]);
            }
        }
        for ( char character : mixedString.toCharArray() )
        {
            if ( !isLetter(character) )
            {
                continue;
            }
            if ( originalStringStack.empty() )
            {
                return false;
            }
            originalStringStack = transferStacksUntilEmpty(originalStringStack,
                                                           character);
        }
        return originalStringStack.empty();
    }

    private Stack<Character> transferStacksUntilEmpty(
            Stack<Character> originalStringStack,
            char character)
    {
        Stack<Character> tempStack = new Stack<Character>();
        while ( !originalStringStack.empty() )
        {
            char poppedChar = originalStringStack.pop();
            if ( character != poppedChar )
            {
                tempStack.push(poppedChar);
            }
        }
        return tempStack;
    }

    public int getValue()
    {
        int totalValue = 0;
        char[] originalStringCharArray = originalString.toCharArray();
        char[] mixedStringCharArray = mixedString.toCharArray();
        for ( int i = 0; i < originalStringCharArray.length; i++ )
        {
            if ( isLetter(originalStringCharArray[i]) )
            {
                for ( int j = 0; j < mixedStringCharArray.length; j++ )
                {
                    if ( originalStringCharArray[i] == mixedStringCharArray[j] )
                    {
                        totalValue += ((i + 1) * (j + 1));
                    }
                }
            }
        }
        return totalValue;
    }

    private boolean isLetter(char character)
    {
        return "abcdefghijklmnopqrstuvwxyz".contains("" + character);
    }
}
